package main

import (
	"encoding/json"
	"fmt"
)

type OrderItem struct {
	ID    string  `json:"id"`
	Name  string  `json:"name"`
	Price float64 `json:"price"`
}

// 小写字段go语言外部无法访问，序列化没有该字段
type Order struct {
	ID string `json:"id"` //``特性/注解  json tag
	// Name       string  `json:"name,omitempty"`
	//Item       *[]OrderItem `json:"item"`
	Item       []OrderItem `json:"item"`
	Quantity   int         `json:"quantity"`
	TotalPrice float64     `json:"total_price"`
}

func main() {

	marshal()

	unmarshal()

	parseNPL()
}

// 序列化
func marshal() {
	o := Order{
		ID: "1234",
		//Name:       "learn go",
		Quantity:   3,
		TotalPrice: 20,
		Item: []OrderItem{
			{ID: "item_1",
				Name:  "learn go",
				Price: 15},
			{ID: "item_2",
				Name:  "learn java",
				Price: 10},
		},
	}
	// fmt.Printf("%v\n", o)
	// fmt.Printf("%+v\n", o)

	//序列化，指针/切片/结构体实例都支持
	b, err := json.Marshal(o)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%s\n", b)
}

// 反序列化
func unmarshal() {
	//使用``字符串换行转义
	s := `{"id":"1234","item":[{"id":"item_1","name":"learn go","price":15},{"id":"item_2","name":"learn java","price":15}],"quantity":3,"total_price":30}`
	var o Order //序列化出来结构实体，不是地址
	err := json.Unmarshal([]byte(s), &o)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", o)
}

func parseNPL() {
	res := `{"result": [
        {"synonym":"","weight":"0.100000","tag":"普通词","word":"请"
        },
        {"synonym":"","weight":"0.100000","tag":"普通词","word":"输入"
        },
        {"synonym":"","weight":"1.000000","tag":"品类","word":"文本"
        }
    ],"success": true
}`

	//any=interface{}
	// m := make(map[string]any) //不建议使用map接收，取值不方便
	//非动态建议做法
	m := struct {
		Result []struct {
			Tag string `json:"tag"`
		} `json:"result"`
	}{} //初始化匿名结构体
	err := json.Unmarshal([]byte(res), &m)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", m)
	// fmt.Printf("%+v\n", m["result"].([]any)[2].(map[string]any)["tag"])
	fmt.Printf("%+v\n", m.Result[2].Tag)
}
